package cn.timeapi.Applet.Mall.CatSquare.common.HandlerInterceptorAdapter;



import cn.timeapi.Applet.Mall.CatSquare.common.Constant;
import cn.timeapi.Applet.Mall.CatSquare.common.ParamsNotNull;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: Vincent Vic
 * @email: vincent-vic@qq.com
 * @time: 2020/9/30 16:39
 */

public class CheckParamsInterceptor  extends HandlerInterceptorAdapter {
    private static Logger LOG = LoggerFactory.getLogger(CheckParamsInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            LOG.warn("UnSupport handler");
            return true;
        }
        //拿到该方法上加了注解的参数名称
        List<String> list = getParamsName((HandlerMethod) handler);
        for (String s : list) {
            //获取到参数名称并判断是否为空
            String parameter = request.getParameter(s);
            if (StringUtils.isEmpty(parameter)){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", Constant.REQUIRED_ARGUMENT.getCode());
                jsonObject.put("msg", "必传参数错误");
                response.setHeader("Content-type", "application/json;charset=UTF-8");
                response.getWriter().write(jsonObject.toJSONString());
                return false;
            }
        }
        //如果拿到的对象为空,说明没有此注解,直接放行
        return true;
    }

    /**
     * 拿到在参数上加了该注解的参数名称
     */
    private List getParamsName(HandlerMethod handlerMethod) {
        Parameter[] parameters = handlerMethod.getMethod().getParameters();
        List<String> list = new ArrayList<String>();
        for (Parameter parameter : parameters) {
            if(parameter.isAnnotationPresent(ParamsNotNull.class)){
                list.add(parameter.getName());
            }
        }
        return list;
    }
}